package com.yaolin.jfinal.ioc;

import java.lang.reflect.Field;

import javax.inject.Inject;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;

/**
 * Controller {@code @Inject} 处理，类似于Spring-struts-plugin
 * @author yaolin
 *
 */
public class IocInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		Field []fields = inv.getController().getClass().getDeclaredFields();
		for (Field field : fields) {
			Inject annotation = field.getAnnotation(Inject.class);
			if (annotation == null)
				continue;
			try {
				field.setAccessible(true);
				if (field.get(inv.getController()) != null)
					continue;// 如果有值了，就不处理了
				Object fieldValue = IocKit.getBean(field.getType());
				if (fieldValue != null) {
					field.set(inv.getController(), fieldValue);
				} else {
					throw new NullPointerException(field.getClass().getName());
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				field.setAccessible(false);
			}
		}
		inv.invoke();
	}
}
